/**
 * 退款管理页面 - 显示状态为3(已取消)的订单，分为已处理和未处理
 */
import React, { useState, useEffect } from 'react';
import { Table, Button, message, Space, Modal, Tabs, Dropdown } from 'antd';
import axios from 'axios';
import html2canvas from 'html2canvas';
import { Document, Packer, Paragraph, TextRun, Table as WordTable, TableRow, TableCell } from 'docx';
import { useTranslation } from '@/utils/i18n';

// 商品数据类型 - 根据hsl.js和hsl copy.js模型定义
interface Product {
  _id: string;
  shopname: string;
  price: number;
  nums: number;
  store: string;
}

// 订单数据类型 - 根据hsl.js和hsl copy.js模型定义
interface OrderData {
  _id: string;
  studentId: Product | string; // 关联商品ID
  quantity: number; // 购买数量
  totalPrice: string; // 订单总价
  customerName: string; // 客户姓名
  customerPhone: string; // 客户电话
  address: string; // 收货地址
  status: number; // 订单状态: 0待处理、1已发货、2已完成、3已取消
  createdAt: string; // 创建时间
}

const OrderRefund: React.FC = () => {
  const { t, locale } = useTranslation();
  const [orders, setOrders] = useState<OrderData[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [products, setProducts] = useState<Product[]>([]); // 商品列表
  const [activeTab, setActiveTab] = useState<string>('pending'); // 当前激活的标签页：'pending'(未处理)、'processed'(已处理)
  const [exportLoading, setExportLoading] = useState(false);

  // 获取商品列表 - 用于显示商品信息
  const fetchProducts = async () => {
    const res = await axios.get('http://localhost:3000/hsl/product/list');
    if (res.data.code === 200) {
      setProducts(res.data.data);
    }
  };

  // 获取订单列表 - 显示状态为3(未处理退款)和4(已处理退款)的订单
  const fetchCancelledOrders = async () => {
    setIsLoading(true);
    try {
      const res = await axios.get('http://localhost:3000/hsl/order/list');
      if (res.data.code === 200) {
        // 过滤状态为3(未处理退款)和4(已处理退款)的订单
        const cancelledOrders = res.data.data
          .filter((order: OrderData) => order.status === 3 || order.status === 4);
        setOrders(cancelledOrders);
      }
    } catch (error: unknown) {
      console.error('获取退款订单列表失败:', error);
      if (error instanceof Error) {
        message.error(error.message || t('order.refund.messages.fetchFailed'));
      } else {
        message.error(t('order.refund.messages.fetchFailed'));
      }
    } finally {
      setIsLoading(false);
    }
  };

  // 获取当前标签页的数据
  const getCurrentOrders = () => {
    return orders.filter(order =>
      activeTab === 'pending' ? order.status === 3 : order.status === 4
    );
  };

  // 处理退款操作 - 根据hsl.js API重写，实现真实的退款处理逻辑
  const handleRefund = (id: string) => {
    Modal.confirm({
      title: t('order.refund.confirm.title'),
      content: t('order.refund.confirm.content'),
      okText: t('order.refund.confirm.ok'),
      cancelText: t('order.refund.confirm.cancel'),
      onOk: async () => {
        try {
          // 显示加载状态
          setIsLoading(true);

          // 根据hsl.js和hsl copy.js模型，退款处理应该调用update API
          // 虽然订单已经是取消状态(3)，但我们需要确保后端系统记录了退款操作
          console.log('处理订单退款:', id);

          // 调用后端API进行退款处理
          // 注意：这里使用update API，并可以考虑传递额外参数标识这是退款操作
          const res = await axios.put(`http://localhost:3000/hsl/order/update/${id}`, {
            status: 4, // 更新为已处理退款状态
            refundProcessed: true // 额外参数标识退款已处理
          });

          if (res.data.code === 200) {
            // 更新订单列表中的状态
            setOrders(prevOrders =>
              prevOrders.map(order =>
                order._id === id
                  ? { ...order, status: 4 }
                  : order
              )
            );

            message.success(t('order.refund.messages.refundSuccess'));

            // 重新获取商品列表，确保库存数据同步（根据hsl.js模型，取消订单时已恢复库存）
            fetchProducts();
          } else {
            message.error(res.data.msg || t('order.refund.messages.refundFailed'));
          }
        } catch (error: unknown) {
          console.error('退款处理失败:', error);
          if (error instanceof Error) {
            message.error(error.message || t('order.refund.messages.refundFailedNetwork'));
          } else {
            message.error(t('order.refund.messages.refundFailed'));
          }
        } finally {
          setIsLoading(false);
        }
      }
    });
  };

  const handleDelete = async (id: string) => {
    try {
      const res = await axios.delete(`http://localhost:3000/hsl/order/delete/${id}`);
      if (res.data.code === 200) {
        message.success(t('order.refund.messages.deleteSuccess'));
        // 刷新订单列表
        fetchCancelledOrders();
      } else {
        message.error(res.data.msg || t('order.refund.messages.deleteFailed'));
      }
    } catch (error: unknown) {
      console.error('订单删除失败:', error);
      if (error instanceof Error) {
        message.error(error.message || t('order.refund.messages.deleteFailedNetwork'));
      } else {
        message.error(t('order.refund.messages.deleteFailed'));
      }
    }
  }

  // 导出为Excel (CSV格式)
  const exportToExcel = () => {
    setExportLoading(true);
    try {
      // 准备CSV数据
      const headers = [
        t('order.refund.table.orderId'),
        t('order.refund.table.productName'),
        t('order.refund.table.productPrice'),
        t('order.refund.table.quantity'),
        t('order.refund.table.totalPrice'),
        t('order.refund.table.customerName'),
        t('order.refund.table.customerPhone'),
        t('order.refund.table.address'),
        t('order.refund.table.createdAt'),
        t('order.refund.table.status'),
      ];
      const rows = [headers];

      // 添加数据行
      getCurrentOrders().forEach(order => {
        const product = getProductInfo(order.studentId);
        rows.push([
          order._id,
          product?.shopname || t('order.refund.messages.unknownProduct'),
          (product?.price || 0).toString(),
          order.quantity.toString(),
          order.totalPrice,
          order.customerName,
          order.customerPhone,
          order.address,
          new Date(order.createdAt).toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN'),
          order.status === 3 ? t('order.refund.status.pending') : t('order.refund.status.processed')
        ]);
      });

      // 生成CSV内容
      const csvContent = rows.map(row =>
        row.map(cell => `"${cell}"`).join(',')
      ).join('\n');

      // 创建下载链接
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      const exportPrefix = activeTab === 'pending' ? t('order.refund.tabs.pending') : t('order.refund.tabs.processed');
      link.download = `${exportPrefix}_${new Date().toISOString().split('T')[0]}.xlsx`;
      link.click();

      message.success(t('order.refund.messages.exportExcelSuccess'));
    } catch (error) {
      console.error('导出Excel失败:', error);
      message.error(t('order.refund.messages.exportExcelFailed'));
    } finally {
      setExportLoading(false);
    }
  };

  // 导出为图片
  const exportToImage = async () => {
    setExportLoading(true);
    try {
      // 创建一个临时的容器来渲染表格数据
      const tableContainer = document.createElement('div');
      tableContainer.style.width = '1200px';
      tableContainer.style.padding = '20px';
      tableContainer.style.backgroundColor = 'white';
      tableContainer.style.position = 'absolute';
      tableContainer.style.left = '-9999px';
      tableContainer.style.top = '-9999px';
      document.body.appendChild(tableContainer);

      // 添加标题
      const title = document.createElement('h2');
      const exportPrefix = activeTab === 'pending' ? t('order.refund.tabs.pending') : t('order.refund.tabs.processed');
      title.textContent = `${exportPrefix} - ${t('order.refund.title')}`;
      title.style.textAlign = 'center';
      title.style.marginBottom = '20px';
      tableContainer.appendChild(title);

      // 添加生成时间
      const timeInfo = document.createElement('p');
      timeInfo.textContent = t('order.refund.messages.generatedAt', {
        time: new Date().toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN'),
      });
      timeInfo.style.textAlign = 'center';
      timeInfo.style.marginBottom = '20px';
      tableContainer.appendChild(timeInfo);

      // 创建表格
      const table = document.createElement('table');
      table.style.width = '100%';
      table.style.borderCollapse = 'collapse';

      // 创建表头
      const thead = document.createElement('thead');
      const headerRow = document.createElement('tr');
      const headers = [
        t('order.refund.table.orderId'),
        t('order.refund.table.productName'),
        t('order.refund.table.productPrice'),
        t('order.refund.table.quantity'),
        t('order.refund.table.totalPrice'),
        t('order.refund.table.customerName'),
        t('order.refund.table.customerPhone'),
        t('order.refund.table.address'),
        t('order.refund.table.createdAt'),
        t('order.refund.table.status'),
      ];
      headers.forEach(headerText => {
        const th = document.createElement('th');
        th.textContent = headerText;
        th.style.border = '1px solid #ddd';
        th.style.padding = '10px';
        th.style.backgroundColor = '#f5f5f5';
        th.style.fontWeight = 'bold';
        headerRow.appendChild(th);
      });
      thead.appendChild(headerRow);
      table.appendChild(thead);

      // 创建表格内容
      const tbody = document.createElement('tbody');
      getCurrentOrders().forEach(order => {
        const product = getProductInfo(order.studentId);
        const row = document.createElement('tr');
        const data = [
          order._id,
          product?.shopname || t('order.refund.messages.unknownProduct'),
          `¥${product?.price || 0}`,
          order.quantity.toString(),
          `¥${order.totalPrice}`,
          order.customerName,
          order.customerPhone,
          order.address,
          new Date(order.createdAt).toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN'),
          order.status === 3 ? t('order.refund.status.pending') : t('order.refund.status.processed')
        ];
        data.forEach(cellText => {
          const td = document.createElement('td');
          td.textContent = cellText;
          td.style.border = '1px solid #ddd';
          td.style.padding = '10px';
          row.appendChild(td);
        });
        tbody.appendChild(row);
      });
      table.appendChild(tbody);
      tableContainer.appendChild(table);

      // 使用html2canvas截图
      const canvas = await html2canvas(tableContainer, {
        scale: 2, // 提高清晰度
        useCORS: true,
        backgroundColor: 'white'
      });

      // 转换为图片并下载
      const link = document.createElement('a');
      link.href = canvas.toDataURL('image/png');
      link.download = `${exportPrefix}_${new Date().toISOString().split('T')[0]}.png`;
      link.click();

      // 清理临时元素
      document.body.removeChild(tableContainer);
      message.success(t('order.refund.messages.exportImageSuccess'));
    } catch (error) {
      console.error('导出图片失败:', error);
      message.error(t('order.refund.messages.exportImageFailed'));
    } finally {
      setExportLoading(false);
    }
  };

  // 导出为Word
  const exportToWord = async () => {
    setExportLoading(true);
    try {
      const exportPrefix = activeTab === 'pending' ? t('order.refund.tabs.pending') : t('order.refund.tabs.processed');

      // 创建Word文档
      const doc = new Document({
        sections: [
          {
            properties: {},
            children: [
              // 添加标题
              new Paragraph({
                children: [
                  new TextRun({
                    text: `${exportPrefix} - ${t('order.refund.title')}`,
                    bold: true,
                    size: 36,
                  }),
                ],
                alignment: 'center',
                spacing: {
                  after: 240,
                },
              }),
              // 添加生成时间
              new Paragraph({
                children: [
                  new TextRun({
                    text: t('order.refund.messages.generatedAt', {
                      time: new Date().toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN'),
                    }),
                    size: 20,
                  }),
                ],
                alignment: 'center',
                spacing: {
                  after: 240,
                },
              }),
              // 创建表格
              new WordTable({
                rows: [
                  // 表头行
                  new TableRow({
                    children: [
                      new TableCell({
                        children: [new Paragraph(t('order.refund.table.orderId'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.refund.table.productName'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.refund.table.productPrice'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.refund.table.quantity'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph(t('order.refund.table.totalPrice'))],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                    ],
                  }),
                  // 数据行
                  ...getCurrentOrders().map(order => {
                    const product = getProductInfo(order.studentId);
                    return new TableRow({
                      children: [
                        new TableCell({
                          children: [new Paragraph(order._id)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(product?.shopname || t('order.refund.messages.unknownProduct'))],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph((product?.price || 0).toString())],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(order.quantity.toString())],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(order.totalPrice)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                      ],
                    });
                  }),
                ],
              }),
            ],
          },
        ],
      });

      // 生成Word文件并下载
      const blob = await Packer.toBlob(doc);
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${exportPrefix}_${new Date().toISOString().split('T')[0]}.docx`;
      link.click();

      message.success(t('order.refund.messages.exportWordSuccess'));
    } catch (error) {
      console.error('导出Word失败:', error);
      message.error(t('order.refund.messages.exportWordFailed'));
    } finally {
      setExportLoading(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    fetchProducts();
    fetchCancelledOrders();
  }, []);

  // 获取订单关联的商品信息
  const getProductInfo = (productId: string | Product) => {
    if (typeof productId === 'object') {
      return productId;
    }
    return products.find(p => p._id === productId) || null;
  };

  // 表格列配置
  const columns = [
    {
      title: t('order.refund.table.orderId'),
      dataIndex: '_id',
      key: '_id',
      ellipsis: true
    },
    {
      title: t('order.refund.table.productName'),
      dataIndex: ['studentId', 'shopname'],
      key: 'shopname',
      render: (_: string, record: OrderData) => {
        const product = getProductInfo(record.studentId);
        return product?.shopname || t('order.refund.messages.unknownProduct');
      }
    },
    {
      title: t('order.refund.table.productPrice'),
      dataIndex: ['studentId', 'price'],
      key: 'price',
      render: (_: string, record: OrderData) => {
        const product = getProductInfo(record.studentId);
        return `¥${product?.price || 0}`;
      }
    },
    {
      title: t('order.refund.table.quantity'),
      dataIndex: 'quantity',
      key: 'quantity'
    },
    {
      title: t('order.refund.table.totalPrice'),
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      render: (price: string) => `¥${price}`
    },
    {
      title: t('order.refund.table.customerName'),
      dataIndex: 'customerName',
      key: 'customerName'
    },
    {
      title: t('order.refund.table.customerPhone'),
      dataIndex: 'customerPhone',
      key: 'customerPhone'
    },
    {
      title: t('order.refund.table.address'),
      dataIndex: 'address',
      key: 'address',
      ellipsis: true
    },
    {
      title: t('order.refund.table.createdAt'),
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time: string) => new Date(time).toLocaleString(locale === 'en-US' ? 'en-US' : 'zh-CN')
    },
    {
      title: t('order.refund.table.actions'),
      key: 'action',
      render: (_: string, record: OrderData) => (
        <Space>
          {record.status === 3 && (
            <Button type="primary" onClick={() => handleRefund(record._id)}>
              {t('order.refund.actions.processRefund')}
            </Button>
          )}
          {record.status === 4 && (
            <Space>
              <Button disabled type="default">
                {t('order.refund.actions.processed')}
              </Button>
              <Button danger onClick={() => handleDelete(record._id)}>{t('order.refund.actions.delete')}</Button>
            </Space>
          )}
        </Space>
      )
    }
  ];

  return (
    <div className="p-6">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-slate-100 transition-colors">{t('order.refund.title')}</h2>
        <p className="text-gray-500 dark:text-slate-400 mt-1 transition-colors">{t('order.refund.subtitle')}</p>
      </div>

      <div className="bg-white dark:bg-slate-900/80 rounded-lg shadow p-6 transition-colors">
        <Button
          type="primary"
          onClick={fetchCancelledOrders}
          className="mb-4"
          loading={isLoading}
        >
          {t('order.refund.refresh')}
        </Button>

        <Dropdown
          menu={{
            items: [
              {
                key: 'excel',
                label: t('order.refund.exportExcel'),
                onClick: exportToExcel
              },
              {
                key: 'image',
                label: t('order.refund.exportImage'),
                onClick: exportToImage
              },
              {
                key: 'word',
                label: t('order.refund.exportWord'),
                onClick: exportToWord
              }
            ]
          }}
        >
          <Button
            type="default"
            disabled={isLoading || exportLoading || getCurrentOrders().length === 0}
            className="ml-4"
          >
            {exportLoading ? t('order.refund.exporting') : t('order.refund.exportData')}
          </Button>
        </Dropdown>

        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            {
              key: 'pending',
              label: t('order.refund.tabs.pending'),
            },
            {
              key: 'processed',
              label: t('order.refund.tabs.processed'),
            },
          ]}
          className="mb-4"
        />

        <Table
          columns={columns}
          dataSource={getCurrentOrders()}
          loading={isLoading}
          rowKey="_id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) =>
              activeTab === 'pending'
                ? t('order.refund.status.unprocessedCount', { count: total })
                : t('order.refund.status.processedCount', { count: total })
          }}
          locale={{
            emptyText: activeTab === 'pending' ? t('order.refund.empty.pending') : t('order.refund.empty.processed')
          }}
        />
      </div>
    </div>
  );
};

export default OrderRefund;

